package org.absolutezero.client.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.google.gwt.core.client.Callback;
import com.google.gwt.user.client.ui.SuggestOracle;
import com.google.gwt.user.client.ui.SuggestOracle.Response;
import com.google.web.bindery.requestfactory.shared.Request;


public class ProductSuggestionOracle extends SuggestOracle
{
    private List<ProductSuggestion> productSuggestions = null;
 
    @Override
    public void requestSuggestions(Request request, Callback callback)
    {
        Response resp = new Response( matchingPeople( request.getQuery(),
                                                      request.getLimit() 
                                                      ) );
 
        callback.onSuggestionsReady(request, resp);
    }
 
    /**
     * 
     * @param query The current text being entered into the suggest box
     * @param limit The maximum number of results to return 
     * @return A collection of people suggestions that match.
     */
     public Collection<ProductSuggestion> matchingPeople(String query, int limit)
     {
         List<ProductSuggestion> matchingProducts = new ArrayList<ProductSuggestion>(limit);
 
         // only begin to search after the user has type two characters
         if ( query.length() >= 1 )
         {
             String prefixToMatch = query.toLowerCase();
 
             int i = 0;
             int s = productSuggestions.size();
             int count = 0;
 
             // Skip forward over all the names that don't match at the beginning of the array.
             while (i < s && count < limit )
             {
            	 if (productSuggestions.get(i).getDisplayString().toLowerCase().startsWith(prefixToMatch)){
            		 matchingProducts.add(productSuggestions.get(i));
            		 count++;
            	 }
            	 
                 i++;
             }
 
 
         }
 
             return matchingProducts;
     }
 
 
 
        /**
         * @param o 
         * @return
         * @see java.util.List#add(java.lang.Object)
         */
         public boolean add(ProductSuggestion o)
         {
             if ( productSuggestions == null )
             {
                productSuggestions = new ArrayList<ProductSuggestion>();
             }
 
             return productSuggestions.add(o);
         }
 
 
 
        /**
         * @param o
         * @return
         * @see java.util.List#remove(java.lang.Object)
         */
         public boolean remove(Object o)
         {
             if ( productSuggestions != null)
             {
                 return productSuggestions.remove(o);
             }
 
             return false;
          }
 
}